package com.jeff.service;

import com.jeff.entity.StorageEntity;
import com.jeff.repository.StorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.util.Random;

/**
 * @author yangjf
 * @ClassName StorageService
 * @Description: TODO
 * @date 2021/8/19 18:22
 */
@Service
public class StorageService {

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private Random random;

    /**
     * 减库存
     *
     * @param commodityCode
     * @param count
     */
    public void deduct(String commodityCode, int count) {
        if (random.nextBoolean()) {
            throw new RuntimeException("异常:模拟业务异常:Storage branch exception");
        }
        StorageEntity storageEntity = storageMapper.selectOneByExample(new Example.Builder(StorageEntity.class)
                .where(WeekendSqls.<StorageEntity>custom().andEqualTo(StorageEntity::getCommodityCode, commodityCode))
                .build());
        storageEntity.setCount(storageEntity.getCount() - count);
        storageMapper.updateByPrimaryKey(storageEntity);
    }
}
